import { FC } from 'react'
import { componentConfGroups, type ComponentConfType } from '../../../components/question-components'
import { Typography } from 'antd'
import styles from './ComponentLib.module.scss'
import { useDispatch } from 'react-redux'
import { componentAction } from '../../../store/components-reducer'
import { nanoid } from 'nanoid'

function GenComponent(c: ComponentConfType) {
  const dispatch = useDispatch()

  const { Component, title, type, defaultProps } = c

  function handleClick() {
    dispatch(componentAction.addComponent({ fe_id: nanoid(), title, type, props: defaultProps }))
  }

  return (
    <div key={type} className={styles.wrapper} onClick={handleClick}>
      <div className={styles.component}>
        <Component {...defaultProps} />
      </div>
    </div>
  )
}

const ComponentLib: FC = () => {
  return (
    <div>
      {componentConfGroups.map((group, index) => {
        const { groupName, components } = group
        return (
          <div key={index}>
            <Typography.Title level={3} style={{ fontSize: '16px', marginTop: index > 0 ? '20px' : 0 }}>
              {groupName}
            </Typography.Title>
            <div>{components.map(GenComponent)}</div>
          </div>
        )
      })}
    </div>
  )
}

export default ComponentLib
